package com.golden.management.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.golden.management.dao.EmployeeMapper;
import com.golden.management.dao.EmployeePositionMapper;
import com.golden.management.domain.EmployeeDO;
import com.golden.management.domain.ResultDO;
import com.golden.management.entity.Employee;
import com.golden.management.entity.EmployeePosition;
import com.golden.management.query.EmployeeExample;
import com.golden.management.query.EmployeePositionExample;
import com.golden.management.service.IEmployeeService;
import com.golden.management.util.BeanUtilsExtends;
import com.golden.management.util.Constant;
import com.golden.management.util.StatusCode;


@RestController
@RequestMapping("/api")
@Service("employeeService")
public class EmployeeServiceImpl implements IEmployeeService {
	
	private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class);
	
	@Autowired
	private EmployeeMapper employeeMapper;
	
	@Autowired
	private EmployeePositionMapper employeePositionMapper;

	@Transactional
	@PostMapping("/employee")
	public ResultDO add(EmployeeDO domain) {
		Employee entity = new Employee();

		// 复制DO到Entity
		ResultDO result = BeanUtilsExtends.copy(entity, domain);

		// 判断复制是否成功
		if (!result.isSuccess())
			return result;

		
		// 设置时间、状态、删除标志
		entity.setCreateTime(Calendar.getInstance().getTime());
		entity.setIsDelete(Constant.VALID.getValue());
		// 成功标志变量
		int r = -1;

		try {
			r = employeeMapper.insertSelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(StatusCode.ADD_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.ADD_EMPLOYEE_ERROR.getMsg());
			result.setSuccess(false);
			return result;
		}

		// 插入标志小于1时报错
		if (r < 1) {
			result.setErrorCode(StatusCode.ADD_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.ADD_EMPLOYEE_ERROR.getMsg());
			result.setSuccess(false);
			return result;
		}
		
		Integer id = entity.getId();
		
		EmployeePosition entity2 = new EmployeePosition();
		entity2.setEmployeeId(id);
		entity2.setPositionId(domain.getPositionId());
		
		r = -1;
		
		try {
			r = employeePositionMapper.insertSelective(entity2);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(StatusCode.ADD_EMPLOYEE_POSITION_ERROR.getCode());
			result.setErrorMsg(StatusCode.ADD_EMPLOYEE_POSITION_ERROR.getMsg());
			result.setSuccess(false);
			return result;
		}
		
		// 插入标志小于1时报错
		if (r < 1) {
			result.setErrorCode(StatusCode.ADD_EMPLOYEE_POSITION_ERROR.getCode());
			result.setErrorMsg(StatusCode.ADD_EMPLOYEE_POSITION_ERROR.getMsg());
			result.setSuccess(false);
			return result;
		}
		
		result.setModel(ResultDO.FIRST_MODEL_KEY, id);
		return result;
	}
	
	@Transactional
	@DeleteMapping("/employee/{id}")
	public ResultDO delete(Integer id) {
		
		ResultDO result = new ResultDO();

		Employee entity = new Employee();

		entity.setId(id);
		entity.setIsDelete(Constant.DELETE.getValue());

		int r = -1;

		try {
			r = employeeMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
			result.setErrorCode(StatusCode.DELETE_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.DELETE_EMPLOYEE_ERROR.getMsg());
			logger.error(e.getMessage());
			return result;
		}

		if (r < 1) {
			result.setSuccess(false);
			result.setErrorCode(StatusCode.DELETE_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.DELETE_EMPLOYEE_ERROR.getMsg());
			return result;
		}
		
		result = deleteMapping(id);
	
		return result;
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	private ResultDO deleteMapping(Integer employeeId) {
		
		ResultDO result = new ResultDO();
		
		EmployeePositionExample example = new EmployeePositionExample();
		example.createCriteria().andEmployeeIdEqualTo(employeeId);
		
		int r = -1;
		
		try {
			r = employeePositionMapper.deleteByExample(example);
		} catch(Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
			result.setErrorCode(StatusCode.DELETE_EMPLOYEE_POSITION_ERROR.getCode());
			result.setErrorMsg(StatusCode.DELETE_EMPLOYEE_POSITION_ERROR.getMsg());
			logger.error(e.getMessage());
			return result;
		}
		
		if (r < 1) {
			result.setSuccess(false);
			result.setErrorCode(StatusCode.DELETE_EMPLOYEE_POSITION_ERROR.getCode());
			result.setErrorMsg(StatusCode.DELETE_EMPLOYEE_POSITION_ERROR.getMsg());
			return result;
		}
		
		return result;
	}

	@Transactional
	@PostMapping("/employee")
	public ResultDO edit(EmployeeDO domain) {
		
		Employee entity = new Employee();

		// 复制DO到Entity
		ResultDO result = BeanUtilsExtends.copy(entity, domain);

		// 判断复制是否成功
		if (!result.isSuccess()) {
			return result;
		}

		// 设置时间、状态、删除标志
		entity.setModifiTime(Calendar.getInstance().getTime());
		
		
		result = deleteMapping(domain.getId());
		
		if(!result.isSuccess()) {
			return result;
		}
		
		// 成功标志变量
		int r = -1;

		try {
			r = employeeMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(StatusCode.EDIT_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.EDIT_EMPLOYEE_ERROR.getMsg());
			result.setSuccess(false);
			return result;
		}

		// 标志小于1时报错
		if (r < 1) {
			result.setErrorCode(StatusCode.EDIT_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.EDIT_EMPLOYEE_ERROR.getMsg());
			result.setSuccess(false);
			return result;
		}
		result.setModel(ResultDO.FIRST_MODEL_KEY, entity.getId());
		return result;
	}

	@GetMapping("/employee/{id}")
	public ResultDO get(Integer id) {
		
		ResultDO result = new ResultDO();

		if (id < 1) {
			result.setSuccess(false);
			result.setErrorCode(StatusCode.GET_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.GET_EMPLOYEE_ERROR.getMsg());
			return result;
		}

		Employee entity = null;

		try {
			entity = employeeMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorCode(StatusCode.GET_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.GET_EMPLOYEE_ERROR.getMsg());
			logger.error(e.getMessage());
			return result;
		}

		if (entity == null) {
			result.setSuccess(false);
			result.setErrorCode(StatusCode.GET_EMPLOYEE_ERROR.getCode());
			result.setErrorMsg(StatusCode.GET_EMPLOYEE_ERROR.getMsg());
			logger.error(StatusCode.GET_EMPLOYEE_ERROR.getMsg() + " 获取的实体数据为空");
			return result;
		}
		
		
		result.setModel(ResultDO.FIRST_MODEL_KEY, getEmployeeDO(entity));
		return result;
	}

	@PostMapping("/employees")
	public ResultDO query(EmployeeExample example) {
		
		ResultDO result = new ResultDO();

		// 是否进行分页
		if (example.isPage()) {
			example.setLimitByPage(example.getStart() + "," + example.getPageRows());
			long count = employeeMapper.countByExample(example);
			result.setModel(ResultDO.SECOND_MODEL_KEY, count);
		}
		
		List<Employee> list = null;
		try {
			list = employeeMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}

		result.setSuccess(true);
		result.setModel(ResultDO.FIRST_MODEL_KEY, getEmployeeDOList(list));
		return result;
	}
	
	/**
	 * 对象拷贝单个实体到对象中
	 * 
	 * @param obj
	 * @return 返回DO对象
	 */
	public EmployeeDO getEmployeeDO(Employee obj) {
		if (obj == null)
			return null;
		EmployeeDO dst = new EmployeeDO();
		return BeanUtilsExtends.copyProperties(dst, obj) ? dst : null;
	}

	/**
	 * 对象拷贝多个实体到列表中
	 * 
	 * @param List
	 * @return List
	 */
	public List<EmployeeDO> getEmployeeDOList(List<Employee> list) {
		List<EmployeeDO> result = new ArrayList<EmployeeDO>();
		if (list != null && !list.isEmpty()) {
			for (Employee org : list) {
				EmployeeDO org1 = new EmployeeDO();
				BeanUtilsExtends.copy(org1, org);
				if (org1 != null) {
					result.add(org1);
				}
			}
		}
		return result;
	}

}
